﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Drawing;
namespace WpfPdfReader
{
    public class FileItemViewModelCollection
    {
        private string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\WpfPdfReader";
        private string FileName = "RecentItem.xml";
        private ObservableCollection<FileItemViewModel> itemCollection = new ObservableCollection<FileItemViewModel>();
        public ObservableCollection<FileItemViewModel> ItemCollection
        {
            get { return this.itemCollection; }
            set { this.itemCollection = value; }
        }

        public FileItemViewModelCollection()
        {
            string folder = this.AppDataFolder;
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }
            FileName = folder + "\\" + FileName;
            if (System.IO.File.Exists(FileName))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(FileName);
                XmlNodeList books = xmldoc.SelectNodes("Books/Book");

                foreach (XmlNode node in books)
                {
                    FileItemModel model = new FileItemModel()
                    {
                        Name = node["Name"].InnerText,
                        FullName = node["FullName"].InnerText,
                        Time = Convert.ToDateTime(node["Time"].InnerText),
                        Page = Convert.ToInt32(node["Page"].InnerText),
                        LastPageBmpPath = node["LastPageBmpPath"].InnerText,
                        TitlePageBmpPath = node["TitlePageBmpPath"].InnerText,
                    };
                    XmlNodeList bookMarks = node.SelectNodes("BookMarks/BookMark");
                    List<BookMark> bookMarkLst = new List<BookMark>();
                    foreach (XmlNode bookMark in bookMarks)
                    {
                        BookMark item = new BookMark
                        {
                            Name = bookMark["Name"].InnerText,
                            Page = Convert.ToInt32(bookMark["Page"].InnerText),
                            PageBmpPath = bookMark["PageBmpPath"].InnerText,
                            Note = bookMark["Note"].InnerText,
                        };
                        bookMarkLst.Add(item);
                    }
                    model.BookMarks = bookMarkLst;

                    this.itemCollection.Add(new FileItemViewModel(model));
                }
            }
        }

        private static readonly int Capacity = 20;
        public void Serialize()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<?xml version=\"1.0\" ?>\n");
            sb.AppendFormat("<Books>\n");

            int index = 0;
            //按照时间倒序排列
            var newItemCollection = ItemCollection.OrderByDescending<FileItemViewModel, DateTime>((p) => p.Time, new FileItemModel());
            foreach (FileItemViewModel p in newItemCollection)
            {
                sb.AppendFormat("{0}\n", p.ToString());
                index++;
                if (index == Capacity)
                    break;
            }

            sb.AppendFormat("</Books>");
            string xml = sb.ToString();

            using (FileStream fs = new FileStream(FileName, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(sb.ToString());
                    sw.Close();
                    fs.Close();
                }
            }
        }

        //public void Add(string fileName)
        //{
        //    var item = ItemCollection.Where((x) => x.FullName == fileName).FirstOrDefault<FileItemViewModel>();
        //    if (item == null)
        //    {
        //        string name = System.IO.Path.GetFileName(fileName);
        //        ItemCollection.Add(new FileItemViewModel() { Name = name, FullName = fileName, Time = DateTime.Now });
        //    }
        //    else
        //    {
        //        item.Time = DateTime.Now;
        //    }
        //}

        public void Add(string fileName, int page, Bitmap titlePageBmp, Bitmap lastPageBmp)
        {
            var item = FindItem(fileName);
            if (item == null)
            {
                string name = System.IO.Path.GetFileName(fileName);
                string folder = System.IO.Path.Combine(AppDataFolder, name);
                CreateFolder(folder);

                string titlePagePath = System.IO.Path.Combine(folder, TitlePage);
                if (titlePageBmp != null)
                {
                    System.Drawing.Image newBmp = ImageHelper.GetThumbnailImage(titlePageBmp, new Size((int)(titlePageBmp.Width * 0.5), (int)(titlePageBmp.Height * 0.5)));
                    //titlePageBmp.Save(titlePagePath);
                    newBmp.Save(titlePagePath);
                }

                ItemCollection.Add(new FileItemViewModel()
                {
                    Name = name,
                    FullName = fileName,
                    Time = DateTime.Now,
                    TitlePageBmpPath = titlePagePath,
                });
            }
            else
            {
                if (lastPageBmp != null)
                {
                    string name = System.IO.Path.GetFileName(fileName);
                    string folder = System.IO.Path.Combine(AppDataFolder, name);

                    string lastPagePath = System.IO.Path.Combine(folder, LastPage);

                    if (!(System.IO.File.Exists(lastPagePath) && page == item.Page))
                    {
                        try
                        {
                            lastPageBmp.Save(lastPagePath);
                        }
                        catch { }
                    }
                    item.LastPageBmpPath = lastPagePath;
                    item.Page = page;
                }

                item.Time = DateTime.Now;
            }
        }

        public void AddBookMark(string fileName, string bookMarkName, int page, Bitmap pageBmp,string note)
        {
            var item = FindItem(fileName);
            if (item != null)
            {
                string name = System.IO.Path.GetFileName(fileName);
                string folder = System.IO.Path.Combine(AppDataFolder, name);
                CreateFolder(folder);

                string PagePath = System.IO.Path.Combine(folder, string.Format("{0}.png", page));
                if (!System.IO.File.Exists(PagePath))
                {
                    try
                    {
                        pageBmp.Save(PagePath);
                    }
                    catch { }
                }
                item.BookMarks.Add(new BookMark() { Name = bookMarkName, Page = page, PageBmpPath = PagePath, Note = note });
            }
        }

        public List<BookMark> GetBookMarks(string fileName)
        {
            var item = FindItem(fileName);
            if (item != null)
                return item.BookMarks;
            else
                return null;
        }

        private void CreateFolder(string folder)
        {
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }
        }

        private const string TitlePage = "TitlePage.png";
        private const string LastPage = "LastPage.png";


        public FileItemViewModel FindItem(string fileName)
        {
            var item = ItemCollection.Where((x) => x.FullName == fileName).FirstOrDefault<FileItemViewModel>();
            return item;
        }
    }
}
